package com.greenold.residing.service.impl;

import java.util.*;

import com.greenold.approvalRecord.domain.ApprovalRecord;
import com.greenold.commen.domain.Elder;
import com.greenold.common.utils.SecurityUtils;
import com.greenold.residing.domain.ApprovalRecordDTO;
import com.greenold.residing.domain.LeaveRequestDTO;
import com.greenold.residing.domain.OrderMessageDTO;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.greenold.residing.mapper.LeaveRequestMapper;
import com.greenold.residing.domain.LeaveRequest;
import com.greenold.residing.service.ILeaveRequestService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 请假管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-13
 */
@Service
public class LeaveRequestServiceImpl implements ILeaveRequestService {
    @Autowired
    private LeaveRequestMapper leaveRequestMapper;

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    /**
     * 查询请假管理
     *
     * @param id 请假管理主键
     * @return 请假管理
     */
    @Override
    public LeaveRequest selectLeaveRequestById(String id) {
        return leaveRequestMapper.selectLeaveRequestById(id);
    }

    /**
     * 查询请假管理列表
     *
     * @param leaveRequest 请假管理
     * @return 请假管理
     */
    @Override
    public List<LeaveRequestDTO> selectLeaveRequestList(LeaveRequest leaveRequest) {
        //根据taskId查询流程实例id 此时的BusinessId是taskId
        String processInstanceId = leaveRequestMapper.getProcessInstanceId(leaveRequest.getBusinessId());
        //把流程实例id set进实体类，此时的BusinessId是流程实例id
        leaveRequest.setBusinessId(processInstanceId);
        //根据businessId查询
        List<LeaveRequestDTO> list = leaveRequestMapper.selectLeaveRequestList(leaveRequest);
        for (LeaveRequestDTO leaveRequestDTO : list) {
            Long userId = SecurityUtils.getUserId();
            leaveRequestDTO.setApprovalUser(userId.toString());
            leaveRequestDTO.setApprovalUserRole(leaveRequestMapper.getUserRole(userId.toString()));
            leaveRequestDTO.setCurrentStep(leaveRequestMapper.getCurrentStep(leaveRequestDTO.getBusinessId()));
        }
        return list;
    }

    /**
     * 新增请假管理
     *
     * @param leaveRequest 请假管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertLeaveRequest(LeaveRequest leaveRequest) {
        //生成单据编号
        String docNo = "QJ" + UUID.randomUUID().toString().replace("-", "").substring(0, 14);;
        leaveRequest.setDocNo(docNo);
        //设置当前用户id
        String userId = SecurityUtils.getUserId().toString();
        leaveRequest.setCreatedBy(userId);  //设置创建人为当前登录用户id
        //获取申请人
        String userName = SecurityUtils.getUsername();
        //创建流程实例
        Map<String, Object> map = new HashMap<>();
        // map.put("nurseGeneralId", "100"); //护理员角色id
        // map.put("nurseSupervisorId", "106"); //护理主管角色id
        // map.put("nurseManagerId", "101"); //护理部长角色id
        map.put("nurseGeneralId", "1"); //护理员角色id
        map.put("nurseSupervisorId", "1"); //护理主管角色id
        map.put("nurseManagerId", "1"); //护理部长角色id
        map.put("leaveDays", leaveRequest.getLeaveDays());
        map.put("careLevel", leaveRequest.getLevelName());
        map.put("processType", 1);  //1请假 2退住 3申请
        map.put("processCode",docNo);
        map.put("processTitle",leaveRequest.getElderName()+"的请假申请");
        map.put("assignee0Name",userName);   //申请人
        map.put("applicationTime",new Date());
        map.put("ops",1);  //1通过 2拒绝
        map.put("status",1);   //状态 1:申请中,2:已完成
        map.put("elderId",leaveRequest.getElderId());
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("leaveRequest", map);
        //查询task代办流程id
        Task task = taskService.createTaskQuery()
                .processDefinitionKey("leaveRequest") //流程定义key
                .taskName("护理员发起请假申请")
                .singleResult();
        //完成当前步骤:护理员发起申请
        taskService.complete(task.getId());
        //把业务id添加到请假表实体类中
        leaveRequest.setBusinessId(processInstance.getId()); //流程实例id
        return leaveRequestMapper.insertLeaveRequest(leaveRequest);
    }

    /**
     * 修改请假管理
     *
     * @param leaveRequest 请假管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateLeaveRequest(LeaveRequest leaveRequest) {
        //修改老人请假状态和床位状态 已返回
        String elderId = leaveRequest.getElderId();
        leaveRequestMapper.updateElderLeaveStatus(elderId,4);
        leaveRequestMapper.updateBedLeaveStatus(elderId,1);
        return leaveRequestMapper.updateLeaveRequest(leaveRequest);
    }

    /**
     * 批量删除请假管理
     *
     * @param ids 需要删除的请假管理主键
     * @return 结果
     */
    @Override
    public int deleteLeaveRequestByIds(String[] ids) {
        return leaveRequestMapper.deleteLeaveRequestByIds(ids);
    }

    /**
     * 删除请假管理信息
     *
     * @param id 请假管理主键
     * @return 结果
     */
    @Override
    public int deleteLeaveRequestById(String id) {
        return leaveRequestMapper.deleteLeaveRequestById(id);
    }

    /**
     * 请假审批
     *
     * @param approvalRecordDTO 审批记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int approval(ApprovalRecordDTO approvalRecordDTO) {
        Map<String,Object> map = new HashMap<>();
        map.put("approvalOpinion", approvalRecordDTO.getApprovalOpinion());   //审批意见
        map.put("approvalStatus", approvalRecordDTO.getApprovalStatus());     //审批状态 1:通过,2:拒绝
        //完成当前步骤:xx审批
        if (approvalRecordDTO.getApprovalStatus().equals("2")){
            System.out.println("===========================");
            System.out.println("拒绝审批");
            System.out.println("===========================");
            map.put("status",2);
            map.put("ops",2);
        }else if (!approvalRecordDTO.getCareLevel().equals("特级护理等级") && approvalRecordDTO.getLeaveDays() < 3){
            System.out.println("===========================");
            System.out.println("主管审批通过");
            System.out.println("===========================");
            map.put("status",2);
            //修改老人请假状态和床位状态为请假中
            String elderId = approvalRecordDTO.getElderId();
            leaveRequestMapper.updateElderLeaveStatus(elderId,2);
            leaveRequestMapper.updateBedLeaveStatus(elderId,2);
        }else {
            Task task = taskService.createTaskQuery()
                    .taskId(approvalRecordDTO.getBusinessId())
                    .singleResult();
            if (task == null) System.out.println("未查询到 taskId 为 " + approvalRecordDTO.getBusinessId() + " 的任务");
            if ("请假审批-护理部部长处理".equals(task.getName())){
                System.out.println("===========================");
                System.out.println("部长审批通过");
                System.out.println("===========================");
                map.put("status",2);
                //修改老人请假状态和床位状态为请假中
                String elderId = approvalRecordDTO.getElderId();
                leaveRequestMapper.updateElderLeaveStatus(elderId,2);
                leaveRequestMapper.updateBedLeaveStatus(elderId,2);
            }
        }
        taskService.complete(approvalRecordDTO.getBusinessId(),map);
        return 1;
    }

    //查询老人详细信息
    @Override
    public OrderMessageDTO selectElderInfoById(Integer id) {
        return leaveRequestMapper.selectElderInfoById(id);
    }

    /**
     * 查询所有老人基本信息
     *
     * @return 所有老人基本信息
     */
    @Override
    public List<Elder> getElderList() {
        return leaveRequestMapper.getElderList();
    }

}
